<script setup lang="ts">
import { reactive } from 'vue'
import { columns, searchFormSchema, useDictTypeId } from './dict.data'
import DictTypeTree from './DictTypeTree.vue'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { dictApi } from '@/api/sys/dictApi'
import { IconEnum } from '@/enums/appEnum'
import { useModal } from '@/components/Modal'
import DictModal from '@/views/sys/dict/DictModal.vue'
import type { DictDeleteReq } from '@/model/sys/dictModel'
import { DictComponentCodes } from '@/enums/componentCodesEnum'

defineOptions({ name: 'DictList' })
const [registerModal, { openModal }] = useModal()
const dictQuery = reactive<Recordable>({})
const [registerTable, { reload }] = useTable({
  title: '字典列表',
  api: dictApi.list,
  columns,
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
    autoSubmitOnEnter: true,
  },
  useSearchForm: true,
  showTableSetting: true,
  showIndexColumn: false,
  actionColumn: {
    width: 140,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
})
function handleAdd() {
  openModal(true, { isUpdate: false })
}

function handleUpdate(record: Recordable) {
  openModal(true, { record, isUpdate: true })
}
const { setDictTypeId } = useDictTypeId()
function handleSelect(dictTypeId = '') {
  dictQuery.dictTypeId = dictTypeId
  setDictTypeId(dictTypeId)
  reload()
}

async function handleDelete(record: Recordable) {
  await dictApi.delete(record as DictDeleteReq)
  reload()
}
</script>

<template>
  <div class="flex">
    <DictTypeTree class="w-1/4 xl:w-1/5" @select="handleSelect" />
    <BasicTable class="w-3/4 xl:w-4/5" :search-info="dictQuery" @register="registerTable">
      <template #toolbar>
        <a-button v-permission="DictComponentCodes.Add" type="primary" :pre-icon="IconEnum.ADD" @click="handleAdd">
          新增
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: IconEnum.EDIT,
                label: '更新',
                permission: DictComponentCodes.Update,
                onClick: handleUpdate.bind(null, record),
              },
            ]"
            :drop-down-actions="[
              {
                icon: IconEnum.PASSWORD,
                danger: true,
                label: '删除',
                permission: DictComponentCodes.Delete,
                popConfirm: {
                  title: '确定?',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
                ifShow: () => !record.buildIn,
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <DictModal @register="registerModal" @success="reload()" />
  </div>
</template>
